package com.tgu.home_action.service.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.facebody.model.v20191230.*;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.tgu.home_action.pojo.ResponseData;
import com.tgu.home_action.pojo.state.ResponseState;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Setter
@ConfigurationProperties(prefix = "oss")
public class AliYunService {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.regionID}")
    private String regionID;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.domain}")
    private String domain;

    private static String DATABASE = "faceDataBase";
    private static String UPDATE_FACE_ENTITY = "UpdateFaceEntity";
    private static String ADD_FACE_ENTITY = "AddFaceEntity";

    public String getUrl(String objectName) {
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }


    /**
     * 上传文件
     */
    public String uploadFile(InputStream inputStream, String objectName) {
        String ret = "上传失败";
        try{
            // 创建上传object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(objectName.substring(objectName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;fileName=" + objectName);

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传网络流。
            ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);

            //获取图片url
            String url = "https://" + domain + "/" + objectName;
            System.out.println("=======================");
            System.out.println("url: " + url);
            // 关闭OSSClient。
            ossClient.shutdown();
            return url;
//            return "https://" + bucketName + "." + endpoint + "/" + objectName;

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 人脸识别一对一
     */
    public Double compareFace(String imageURLA, String imageURLB) throws ClientException {
        boolean flag = false;

        //目前区域只开通了华东2(上海)
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CompareFaceRequest request = new CompareFaceRequest();
        request.setRegionId("cn-shanghai");
        request.setImageURLA(imageURLA);
        request.setImageURLB(imageURLB);
        CompareFaceResponse response = client.getAcsResponse(request);
        System.out.println(new Gson().toJson(response));
        return Double.valueOf(response.getData().getConfidence());
    }

    /**
     * 判断是否为一个老人
     */
    public ResponseData<Map<String,Object>> isOldMan(String imgUrl) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        RecognizeFaceRequest request = new RecognizeFaceRequest();
        request.setRegionId("cn-shanghai");
        request.setImageURL(imgUrl);
        try {
            RecognizeFaceResponse response = client.getAcsResponse(request);
            System.out.println(response.getData());
            System.out.println(response.getData().getAgeList());
            List<Integer> ageList = response.getData().getAgeList();
            List<Integer> sexList = response.getData().getGenderList();
            Map<String,Object> data=new HashMap<>();
            if (ageList == null || ageList.size() == 0) {
                data.put("isOldMan",false);
                return new ResponseData<>("没有检测到人脸", ResponseState.ERROR.getValue(), data);
            } else if (ageList.size() != 1) {
                data.put("isOldMan",false);
                return new ResponseData<>("检测到多个人脸", ResponseState.ERROR.getValue(), data);
            }
            Integer age = ageList.get(0);
            Integer sex = sexList.get(0);
            data.put("age",age);
            data.put("sex",sex);
            if (age < 45) {
                data.put("isOldMan",false);
                return new ResponseData<>("照片上人脸不是老人", ResponseState.ERROR.getValue(), data);
            }
            data.put("isOldMan",true);
            return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), data);
        } catch (ClientException e) {
            e.printStackTrace();
            Map<String,Object> data=new HashMap<>();
            data.put("isOldMan",false);
            return new ResponseData<>("未检测到人脸信息", ResponseState.ERROR.getValue(), data);
        }
    }

    /**
     * 插入人脸样本
     */
    public void addFaceEntity(String entityId) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        AddFaceEntityRequest addFaceEntityRequest = new AddFaceEntityRequest();
        addFaceEntityRequest.setActionName(ADD_FACE_ENTITY);
        addFaceEntityRequest.setDbName(DATABASE);
        addFaceEntityRequest.setEntityId(entityId);
        try {
            AddFaceEntityResponse response = client.getAcsResponse(addFaceEntityRequest);
            System.out.println(response);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新人脸样本
     */
    public void updateFaceEntity(String entityId, String[] labelArray) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        AddFaceEntityRequest addFaceEntityRequest = new AddFaceEntityRequest();
        addFaceEntityRequest.setActionName(ADD_FACE_ENTITY);
        addFaceEntityRequest.setDbName(DATABASE);
        addFaceEntityRequest.setEntityId(entityId);
        StringBuilder labels = new StringBuilder();
        for (int i = 0; i < labelArray.length; i++) {
            if (i != 0) {
                labels.append(",");
            }
            labels.append(labelArray[i]);
        }
        addFaceEntityRequest.setLabels(labels.toString());
        try {
            client.doAction(addFaceEntityRequest);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 人脸搜索（单个数据库）
     */
    public List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> searchFace(String imgUrl, Integer limit) throws ClientException {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        SearchFaceRequest searchFaceRequest = new SearchFaceRequest();
        searchFaceRequest.setDbName(DATABASE);
        searchFaceRequest.setImageUrl(imgUrl);
        searchFaceRequest.setLimit(limit);
        SearchFaceResponse response = client.getAcsResponse(searchFaceRequest);
        SearchFaceResponse.Data.MatchListItem matchListItem = response.getData().getMatchList().get(0);
        if (matchListItem != null) {
            return matchListItem.getFaceItems();
        }
        return null;
    }

    /**
     * 添加人脸数据
     */
    public void addFace(String imgUrl, String entityId) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        AddFaceRequest request = new AddFaceRequest();
        request.setDbName(DATABASE);
        request.setImageUrl(imgUrl);
        request.setEntityId(entityId);
        try {
            AddFaceResponse response = client.getAcsResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除人脸样本
     */
    public void deleteFaceEntity(String entityId) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        DeleteFaceEntityRequest request = new DeleteFaceEntityRequest();
        request.setDbName(DATABASE);
        request.setEntityId(entityId);
        try {
            DeleteFaceEntityResponse response = client.getAcsResponse(request);
            System.out.println(response);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
